import MySQLdb
import sys
import time

# usage example: $python importer/ids.py pwd sample_ori_ids sample/IDS_log.txt

DEBUG = 2

YEAR = 2011 # omitted in the log, so append it

if __name__ == '__main__':
    db = MySQLdb.connect(host="rome.cs.vt.edu", port=5801, user="fusetester", passwd=sys.argv[1], db="fusebox")

    tablename = sys.argv[2]
    filename = sys.argv[3]
    hfile = open(filename)

    counter = 1
    for block in hfile.read().split('\n\n'):
        if block != '':
            lines = block.split('\n')
            if lines[0] == '':
                lines = lines[1:]

            if DEBUG >= 3:
                print '#### LINES ####'
                print lines

            rule = lines[0][6:-5]
            ruleN, ruleV = rule.split('] ') # rule No. and rule violation discription
            if len(ruleV) > 1024 and DEBUG >= 1:
                print 'Warning: rule discription is out of space!'

            # notice: there is a ' ' at the end of lines[1]
            cate = 'None'
            tmp = lines[1].split('] [')
            if len(tmp) == 1:
                priority = lines[1][11:-2]
            elif len(tmp) ==2:
                cate = tmp[0][17:]
                priority = tmp[1][10:-2]
            else:
                print 'Error with line "cate, priority"'

            timestr, source, tmpnone, dest = lines[2].split()
            # handle source
            sourcetuple = source.split(':')
            sourceip = sourcetuple[0]
            sourceport = 0
            if len(sourcetuple) == 2:
                sourceport = sourcetuple[1]
            # handle dest
            desttuple = dest.split(':')
            destip = desttuple[0]
            destport = 0
            if len(desttuple) == 2:
                destport = desttuple[1]

            timestr = timestr.split('.')[0] # get rid of milliseconds
            timestr = str(YEAR) + '/' + timestr # append year to strip
            unixdate = int(time.mktime(time.strptime(timestr, "%Y/%m/%d-%H:%M:%S")))

            db.query('INSERT INTO %s (rulenum, ruledis, cate, priority, date, sip, sport, dip, dport) VALUES ("%s", "%s", "%s", %s, %d, "%s", %s, "%s", %s)' % (tablename, ruleN, ruleV, cate, priority, unixdate, sourceip, sourceport, destip, destport))

            if DEBUG >= 2 and counter % 100 == 0:
                print '#### END %d ####' % (counter)
            counter += 1

    db.close()

